﻿// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
//
// A Status encapsulates the result of an operation.  It may indicate success,
// or it may indicate an error with an associated error message.
//
// Multiple threads can invoke const methods on a Status without
// external synchronization, but if any of the threads may call a
// non-const method, all threads accessing the same Status must use
// external synchronization.

#ifndef STORAGE_LEVELDB_INCLUDE_STATUS_H_
#define STORAGE_LEVELDB_INCLUDE_STATUS_H_

#include <cstring>
#include <string>

class Status {
public:
    // 默认构造函数，表示成功状态
    Status() : state_(nullptr) {}

    ~Status() { delete[] state_; }

    // 拷贝构造函数
    Status(const Status& rhs);
    
    // 移动构造函数
    Status(Status&& rhs);

    // 赋值运算符重载函数
    Status& operator=(const Status& rhs);
    
    // 移动赋值运算符重载函数
    Status& operator=(Status&& rhs);

    // 构造函数，用于创建特定错误码的状态对象
    static Status NotFound(const char* msg);
    static Status Corruption(const char* msg);
    static Status NotSupported(const char* msg);
    static Status InvalidArgument(const char* msg);
    static Status IOError(const char* msg);

    // 返回一个成功状态对象
    static Status OK() { return Status(); }

    // 判断当前状态是否为成功状态
    bool ok() const { return (state_ == nullptr); }

    // 判断当前状态是否为指定类型的错误状态
    bool IsNotFound() const;
    bool IsCorruption() const;
    bool IsIOError() const;
    bool IsNotSupportedError() const;
    bool IsInvalidArgument() const;

    // 返回状态信息的字符串表示
    std::string ToString() const;

private:
    enum Code {
        kOk = 0,
        kNotFound = 1,
        kCorruption = 2,
        kNotSupported = 3,
        kInvalidArgument = 4,
        kIOError = 5
    };

    // 构造函数，用于创建指定错误码和错误信息的状态对象
    Status(Code code, const char* msg);

    Code code() const {
        return (state_ == nullptr) ? kOk : static_cast<Code>(state_[4]);
    }

    // 将状态信息复制一份
    char* CopyState(const char* state);

    // OK status has a null state_.  Otherwise, state_ is a new[] array
    // of the following form:
    //    state_[0..3] == length of message
    //    state_[4]    == code
    //    state_[5..]  == message
    const char* state_;
};


#endif // STORAGE_LEVELDB_INCLUDE_STATUS_H_
